package com.td.core.communication;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Sender extends Thread {

	private Socket socket;
	private ObjectOutputStream output;
	
	private List<Sendable<?>> toSend;
	
	public Sender(Socket s) throws IOException {
		socket = s;
		if(s != null) {
			output = new ObjectOutputStream(socket.getOutputStream());
			output.flush();
		}
		
		toSend = new ArrayList<Sendable<?>>();
	}
	
	public void run() {
		while(!interrupted()) {
			synchronized (toSend) {
				if(toSend != null) {
					try {
						Iterator<Sendable<?>> it = toSend.iterator();
						while(it.hasNext()) {
							output.writeObject(it.next());
						}
						output.flush();
						output.reset();
					} catch (IOException e) {
						e.printStackTrace();
					}
					finally {
						toSend.clear();
					}
				}	
			}
			
			try {
				sleep(10);
			} catch (InterruptedException e) {
				this.interrupt();
			}
		}
		try {
			output.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			output = null;
			socket = null;
		}
		
	}
	
	public void send(Sendable<?> obj) {
		synchronized (toSend) {
			toSend.add(obj);	
		}
	}
}
